<?php
namespace app\admin\controller\v1;
use app\admin\Adminbase;
use think\console\command\make\Model;
use think\Db;
use app\common\model\ShopStaffWages;


class ShopStaff extends Adminbase 
{
	
	/**
	* 添加员工
	* /admin/v1/shop_staff/add
	* 需要登录 
	* @is_need_login true
	*/
	public function add($data,$shop_id){
		$request = request();
		$userId = $request ->userId;
		$param = json_decode($data,true);
		try {
			$res = model("shop_staff")
				->where('shop_id',$shop_id)
				->where('id','not in',array_column($param,"id"))
				->update(['is_del'=>1]);
				
			$codes =  array_column($param, 'code'); 
			if(count($codes) != count(array_unique($codes))){
				$repeat_arr = array_diff_assoc ( $codes, array_unique($codes) );
				return $this->ReError('员工账号重复：'. join(",",$repeat_arr) );	
			}
				
			foreach($param as $key=>$val){
				if( !$val['id'] && model("shop_staff")->where('code',$val['code'] )->find() ){
					return $this->ReError('员工账号已存在：'.$val['code']);	
				}
			}	
			
			$res = model("shop_staff")->allowField(true)->saveAll($param);
			
			return $this->ReSucess();	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}


    /**
     * 添加其他工资
     * /admin/v1/shop_staff/add
     * 需要登录
     * @is_need_login true
     */
    public function addOtherStaff($id,$formData,$staffData){
        $param = json_decode($staffData,true);

        $sum_other_wages=0;
        $total_wages=0;
        try {

            //累计其他工资，全部变成四舍五入
            $total_wages+=round($formData['base_yj'], 2);
            $total_wages+=round($formData['get_yj'], 2);
            $total_wages+=round($formData['base_pay'], 2);
            $total_wages+=round($formData['ordinary_tc'], 2);
            $total_wages+=round($formData['service_tc'], 2);
            $total_wages+=round($formData['attendance'], 2);

            //将其数列化
            foreach ($param as $k=>$v){
                $sum_other_wages+=$v['money'];
            }


            model('shop_staff_wages')->where('id',$id)->update([
            	'other_wages'=>$param,
            	'other_sum_wages'=>$sum_other_wages,
                'total_wages'=> round($total_wages+$sum_other_wages, 2)
            ]);

            //变更员工基本工资和保底业绩
            model('shop_staff')->where('id',$formData['staff_id'])->update([
                'base_yj'=>$formData['base_yj'],
                'base_pay'=>$formData['base_pay']
            ]);

            return $this->ReSucess();
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 显示其他工资
     * /admin/v1/shop_staff/showOtherStaff
     * 需要登录
     * @is_need_login true
     */
    public function showOtherWages(){
        $request = request();
        $keyword_array = json_decode( $this->request->param('keyWord') , true );
        $wagesId='';
        foreach($keyword_array['filter'] as $k=>$v){
            if( $v['field']=='wages_id' ){
                $wagesId=$v['value'];
            }
        }
        try {
          	$wages = model('common/shop_staff_wages')->where('id',$wagesId)->value('other_wages');
          	return [
          		"data"=> json_decode($wages,true) ?: [],
          	];
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
	
	
	/**
	* 获取最大id
	* /admin/v1/shop_staff/getMaxId
	* 需要登录 
	* @is_need_login true
	*/
	public function getMaxId(){
		try {
			return $this->ReSucess( model("shop_staff")->max('id') );	
		} catch (\Exception $e) {
			return $this->ReError($e->getMessage());	
		}
	}

    /**
     * 获取本月的上个月
     * /admin/v1/shop_staff/getLastMonth
     * 需要登录
     * @is_need_login true
     */
    public function getLastMonth(){
        try {
            return $this->ReSucess( model("shop_staff")->max('id') );
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 获取当前日期的前五个月
     * /admin/v1/shop_staff/getFiveMonth
     * 需要登录
     * @is_need_login true
     */
    public function getFiveMonth(){
        try {

            $arr=[];
            $year=date('Y');
            $yue=date('m');
            $sign=5;
            for($i=0;$i<$sign;$i++){

                $month=mktime(0,0,0,$yue-($i+1),1,$year);
                $arr[]=[
                    'value'=>date('Y-m',$month),
                    'label'=>date('n',$month).'月'
                ];

            }

            return $arr;


        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }
    /**
     * 获取是否存在了工资表里面了。
     * /admin/v1/shop_staff/getown
     * 需要登录
     * @is_need_login true
     */
    public function getown($staff_id,$months){
        try {
        	
        	$res = model('shop_staff_wages')
        		->where('staff_id',$staff_id)
        		->where('months',$months)
        		->find();
        	
          	return $this->ReSucess($res);

        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }

    /**
     * 获取员工工资表
     * /admin/v1/shop_staff/getShopStaff
     * 需要登录
     * @is_need_login true
     */

    public function getShopStaffWages(){
        try {
        	
            $keyword_array = json_decode($this->request->param('keyWord'),true);
            $shop_id='';
            $key_word= '';
            $moth='';
           	foreach($keyword_array['filter'] as $k=>$v){
                if($v['field']=='shop_id'){
                    $shop_id=$v['value'];
                }
                if($v['field']=='name,code,gh,base_yj'){
                    $key_word=$v['value'];
                }
                if($v['field']=='months'){
                    $moth=$v['value'].'-01';
                }
           	}

            $str="";
            $str.=" and shop_id=".$shop_id;

            if($key_word){
                $str.=" and name like '%$key_word%'";
            }

            $str_limit=" order by gh asc "."limit ".($this->request->post('pageIndex')-1) * ( $this->request->post('pageSize')).",".$this->request->post('pageSize');

            $sql=" select * from (
                        select
							a.uid,a.shop_id,a.gh,a.id,a.name as staff_name,a.code,a.base_pay,a.base_yj
	                        ,ifnull(b.yj,0.00)+ifnull(c.yj,0.00) as get_yj
	                        ,sum(ifnull(g.service_score,0.00)) as service_score
	                        ,ifnull(b.service_tc,0.00) as service_tc
	                        ,ifnull(c.ordinary_tc,0.00) as ordinary_tc
	                        ,(ifnull(b.service_tc,0)+IFNULL(c.ordinary_tc,0)) as online_tc
							,ifnull(h.attendance,0.00) as attendance
							,ifnull(h.other_sum_wages,0.00) as other_sum_wages
						    ,if(DATE_FORMAT('$moth','%Y%m')=DATE_FORMAT(date_add(curdate(),interval -1 month),'%Y%m'),1,0) as shows
						    ,case when h.id<>0 then 1 else 0  end is_edit
	                        ,(ifnull(a.base_yj,0.00)+ifnull(get_yj,0.00)+ifnull(a.base_pay,0.00)+(ifnull(b.service_tc,0.00)+ifnull(c.ordinary_tc,0.00))+ifnull(h.attendance,0.00)+ifnull(h.other_sum_wages,0.00)) as total_wages  
					  	from xw_shop_staff  as a

				    	left join (
		                    select sum(i.number) as service_tc,i.uid,i.add_time,sum(pay_price) as yj 
		                    from xw_order a
							LEFT JOIN xw_user_bill i on i.link_id = a.order_no
						  	where  i.pm=1 and i.`status`=1 
						  	and i.type='rake-back' 
						  	and i.category='brokerage'
						  	and a.is_pay=1 
						  	and a.is_del=0 
						  	and a.status>=0 
						  	and DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('$moth','%Y%m' )  
						  	and a.type<>0
							GROUP BY a.uid
			        	)	b  on b.uid = a.uid 
			        
						left join (
				            select sum(i.number) as ordinary_tc,i.uid,i.add_time,sum(pay_price) as yj 
				            from xw_order a
							LEFT JOIN xw_user_bill i on i.link_id = a.order_no
							where  i.pm=1 
							and i.`status`=1 
							and i.type='rake-back' 
							and i.category='brokerage'
							and a.is_pay=1 
							and a.is_del=0 
							and a.status>=0 
							and DATE_FORMAT(a.add_time,'%Y%m') = DATE_FORMAT('$moth','%Y%m' ) 
							and a.type=0
							GROUP BY a.uid
				        ) c  on c.uid = a.uid 
			        
						left join xw_shop_yy_order as e on e.staff_id=a.id and e.`status`=1 and DATE_FORMAT(e.date,'%Y%m') = DATE_FORMAT('$moth','%Y%m' )
						left join xw_user_yg_proj as f on f.id=e.proj_id 
						left join xw_goods_specs as g on g.id=f.specs_id
						left join xw_shop_staff_wages as h on h.staff_id=a.id and DATE_FORMAT(date_add(DATE_FORMAT(h.add_time,'%Y-%m-%d'),interval -1 month),'%Y%m')   = DATE_FORMAT('$moth','%Y%m' )
						
                       GROUP BY gh    
				) a where (1=1 $str)".$str_limit;

            $tables = \Db::query($sql);

            $data["total"]= count($tables);
            $data["data"]= $tables;
            return $data;
        } catch (\Exception $e) {
            return $this->ReError($e->getMessage());
        }
    }



}



